using System.Collections.Generic;
using FlexiCommerce.Components;

namespace FlexiCommerce.Collections
{
	/// <summary>
	/// Creates a hierarchy of content items from a certain level and downwards.
	/// </summary>
    public class TreeHierarchyBuilder : HierarchyBuilder
    {
        private readonly HierarchicalPersistenceItem rootItem;
        private readonly int maxDepth;

        public TreeHierarchyBuilder(HierarchicalPersistenceItem rootItem)
            : this(rootItem, int.MaxValue)
        {
        }

        public TreeHierarchyBuilder(HierarchicalPersistenceItem rootItem, int maxDepth)
        {
            this.rootItem = rootItem;
            this.maxDepth = maxDepth;
        }

        public override HierarchyNode<HierarchicalPersistenceItem> Build()
        {
            return BuildHierarchyTree(rootItem, maxDepth);
        }

        protected virtual HierarchyNode<HierarchicalPersistenceItem> BuildHierarchyTree(HierarchicalPersistenceItem currentItem, int remainingDepth)
        {
            HierarchyNode<HierarchicalPersistenceItem> node = new HierarchyNode<HierarchicalPersistenceItem>(currentItem);
            if (remainingDepth > 1)
            {
                foreach (HierarchicalPersistenceItem childItem in GetChildren(currentItem))
                {
                    node.Children.Add(BuildHierarchyTree(childItem, remainingDepth - 1));
                }
            }
            return node;
        }
    }
}